package org.chen.payment.controller;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.payment.dto.PaymentCallbackRequest;
import org.chen.payment.service.PaymentCallbackService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@CrossOrigin
public class PaymentCallbackController {
    
    private final PaymentCallbackService paymentCallbackService;

    /**
     * 支付回调接口 - GET请求
     * @param pid 商户ID
     * @param trade_no 易支付订单号
     * @param out_trade_no 商户订单号
     * @param type 支付方式
     * @param name 商品名称
     * @param money 商品金额
     * @param trade_status 支付状态
     * @param param 业务扩展参数
     * @param sign 签名
     * @param sign_type 签名类型
     * @return success或FAIL
     */
    @GetMapping("/notify_url")
    public ResponseEntity<String> paymentCallback(
            @RequestParam Integer pid,
            @RequestParam String trade_no,
            @RequestParam String out_trade_no,
            @RequestParam String type,
            @RequestParam String name,
            @RequestParam String money,
            @RequestParam String trade_status,
            @RequestParam(required = false) String param,
            @RequestParam String sign,
            @RequestParam(defaultValue = "MD5") String sign_type) {

        try {
            log.info("收到GET回调请求 - 订单号: {}, 支付状态: {}", out_trade_no, trade_status);

            // 构建请求对象
            PaymentCallbackRequest request = new PaymentCallbackRequest();
            request.setPid(pid);
            request.setTradeNo(trade_no);
            request.setOutTradeNo(out_trade_no);
            request.setType(type);
            request.setName(name);
            request.setMoney(money);
            request.setTradeStatus(trade_status);
            request.setParam(param);
            request.setSign(sign);
            request.setSignType(sign_type);

            log.info("收到GET回调请求: {}", request);

            // 手动验证必填参数
            if (pid == null || trade_no == null || out_trade_no == null ||
                    type == null || name == null || money == null ||
                    trade_status == null || sign == null) {
                log.error("必填参数缺失");
                return ResponseEntity.ok("fail");
            }

            String result = paymentCallbackService.handlePaymentCallback(request);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("支付回调处理异常: ", e);
            return ResponseEntity.ok("fail");
        }
    }
}